package com.jwater.core.manager.master.monitor;

import com.jwater.core.manager.common.model.AlarmInfo;
import com.jwater.core.manager.common.model.ReportInfo;
import com.jwater.core.manager.common.model.SystemInfo;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * @description:
 * @author: jnner
 * @createDate: 2021/3/22
 * @version: 1.0
 */
public class MonitorManager {
    private Map<String, ConcurrentLinkedDeque<ReportInfo>> reportInfoCache = new ConcurrentHashMap<>();
    private Map<String, ConcurrentLinkedDeque<SystemInfo>> systemInfoCache = new ConcurrentHashMap<>();
    private Map<String, AlarmInfo> alarmInfoCache = new ConcurrentHashMap<>();

    public void addAlarmInfo(AlarmInfo alarmInfo) {
        alarmInfoCache.put(alarmInfo.getType(), alarmInfo);
    }

    public void removeAlarmInfo(String type) {
        alarmInfoCache.remove(type);
    }

    public List<AlarmInfo> getAllAlarmInfo() {
        List<AlarmInfo> list = new ArrayList<>();
        for (Map.Entry<String, AlarmInfo> en : alarmInfoCache.entrySet()) {
            list.add(en.getValue());
        }
        return list;
    }

    public void addReportInfo(ReportInfo reportInfo) {
        ConcurrentLinkedDeque<ReportInfo> list = reportInfoCache.get(reportInfo.getKey());
        if (list == null) {
            list = new ConcurrentLinkedDeque<>();
            reportInfoCache.put(reportInfo.getKey(), list);
        }
        if (list.size() > 30) {
            list.removeFirst();
        }
        list.addLast(reportInfo);
    }

    public ReportInfo getReportInfo(String key) {
        ConcurrentLinkedDeque<ReportInfo> list = reportInfoCache.get(key);
        if (list != null && !list.isEmpty()) {
            return list.peekLast();
        }
        return null;
    }

    public void addSystemInfo(SystemInfo systemInfo) {
        ConcurrentLinkedDeque<SystemInfo> list = systemInfoCache.get(systemInfo.getHost());
        if (list == null) {
            list = new ConcurrentLinkedDeque<>();
            systemInfoCache.put(systemInfo.getHost(), list);
        }
        if (list.size() > 60) {
            list.removeFirst();
        }
        list.addLast(systemInfo);
    }

    public List<SystemInfo> getAllSystemInfo() {
        List<SystemInfo> list = new ArrayList<>();
        for (Map.Entry<String, ConcurrentLinkedDeque<SystemInfo>> en : systemInfoCache.entrySet()) {
            if (en.getValue().isEmpty()) {
                continue;
            }
            list.add(en.getValue().peekLast());
        }
        return list;
    }

}
